<template>
    <el-container class="chat-container">
        <!-- 左侧会诊列表 -->
        <el-aside width="300px" class="left-panel">
            <div class="consultation-header">
                <el-button type="primary" @click="showCreateDialog" v-if="isPatient">
                    新建会诊
                </el-button>
            </div>
            <el-scrollbar>
                <div v-for="consult in consultations" :key="consult.consultationId" class="consult-item"
                    :class="{ active: activeConsult?.consultationId === consult.consultationId }"
                    @click="selectConsultation(consult)">
                    <div class="consult-info">
                        <h4>{{ consult.chiefComplaint }}</h4>
                        <p>医生ID: {{ consult.doctorId }}</p>
                        <p>状态: {{ consult.endedAt ? '已结束' : '进行中' }}</p>
                    </div>
                </div>
            </el-scrollbar>
        </el-aside>

        <!-- 右侧聊天区域 -->
        <el-main class="right-panel">
            <template v-if="activeConsult">
                <div class="chat-header">
                    <h3>{{ activeConsult.chiefComplaint }}</h3>
                    <el-button v-if="!activeConsult.endedAt && isDoctor" type="danger" @click="endConsultations">
                        结束会诊
                    </el-button>
                </div>

                <!-- 修改后的消息区域 -->
                <el-scrollbar class="message-area" ref="scrollbar">
                    <div v-for="msg in messages" :key="msg.messageId"
                        :class="['message-bubble', msg.senderId === currentUserId ? 'self' : 'other']">
                        <!-- 新增消息ID显示 -->
                        <span class="message-id">ID: {{ msg.messageId }}</span>
                        <div class="message-content">
                            <p>{{ msg.messageContent }}</p>
                            <!-- 修改时间格式 -->
                            <span class="time">{{ formatTime(msg.sentAt) }}</span>
                        </div>
                    </div>
                </el-scrollbar>

                <div class="input-area" v-if="!activeConsult.endedAt">
                    <el-input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessages" />
                    <el-button type="primary" @click="sendMessages">发送</el-button>
                </div>
            </template>

            <div v-else class="empty-state">
                <el-empty description="请从左侧选择会诊或创建新会诊" />
            </div>
        </el-main>

        <!-- 新建会诊对话框 -->
        <el-dialog v-model="createDialogVisible" title="新建会诊">
            <el-form :model="newConsultation">
                <el-form-item label="医生ID" required>
                    <el-input-number v-model="newConsultation.doctorId" />
                </el-form-item>
                <el-form-item label="主诉" required>
                    <el-input v-model="newConsultation.chiefComplaint" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createConsultations">创建</el-button>
            </template>
        </el-dialog>
    </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import {
    createConsultation,
    getConsultation,
    sendMessage,
    receiveMessage,
    getConsultationList,
    endConsultation
} from '@/api/consultation'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 用户信息（需要根据实际登录状态获取）
const currentUserId = ref(localStorage.getItem('id'))
const userRole = ref(localStorage.getItem('role')) // 或 'doctor'

// 响应式数据
const consultations = ref([])
const activeConsult = ref(null)
const messages = ref([])
const newMessage = ref('')
const createDialogVisible = ref(false)
const newConsultation = reactive({
    doctorId: null,
    chiefComplaint: ''
})

// 计算属性
const isPatient = computed(() => userRole.value === 'patient')
const isDoctor = computed(() => userRole.value === 'doctor')

// 初始化加载
onMounted(async () => {
    await loadConsultations()
    setupPolling()
})

// 加载会诊列表
const loadConsultations = async () => {
    try {
        const res = await getConsultationList(currentUserId.value, userRole.value)
        consultations.value = res.data
    } catch (error) {
        ElMessage.error('加载会诊列表失败')
    }
}

// 选择会诊
const selectConsultation = async (consult) => {
    activeConsult.value = consult
    await loadMessages()
    scrollToBottom()
}

// 修改后的 loadMessages 方法
const loadMessages = async () => {
  if (!activeConsult.value) return

  try {
    const res = await receiveMessage(activeConsult.value.consultationId)
    if (res.code === '000') {
      // 添加排序逻辑
      messages.value = res.data.sort((a, b) => 
        new Date(a.sentAt) - new Date(b.sentAt)
      )
      scrollToBottom()
    }
  } catch (error) {
    ElMessage.error('加载消息失败')
  }
}

// 修改时间格式化方法（显示更简洁的时间）
const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}

// 发送消息
const sendMessages = async () => {
    if (!newMessage.value.trim()) return

    try {
        await sendMessage({
            consultationId: activeConsult.value.consultationId,
            senderId: currentUserId.value,
            contentType: 'text',
            messageContent: newMessage.value
        })
        await loadMessages()
        newMessage.value = ''
        scrollToBottom()
    } catch (error) {
        ElMessage.error('发送消息失败')
    }
}

// 创建会诊
const createConsultations = async () => {
    try {
        await createConsultation({
            patientId: currentUserId.value,
            doctorId: newConsultation.doctorId,
            chiefComplaint: newConsultation.chiefComplaint
        })
        createDialogVisible.value = false
        await loadConsultations()
        ElMessage.success('会诊创建成功')
    } catch (error) {
        ElMessage.error('创建会诊失败')
    }
}

// 结束会诊
const endConsultations = async () => {
    try {
        await endConsultation(activeConsult.value.consultationId)
        activeConsult.value.endedAt = new Date().toISOString()
        ElMessage.success('会诊已结束')
    } catch (error) {
        ElMessage.error('结束会诊失败')
    }
}

// 自动滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        const scrollbar = document.querySelector('.message-area')
        if (scrollbar) scrollbar.scrollTop = scrollbar.scrollHeight
    })
}

// 轮询消息更新
let pollInterval
const setupPolling = () => {
    pollInterval = setInterval(async () => {
        if (activeConsult.value && !activeConsult.value.endedAt) {
            await loadMessages()
        }
    }, 5000)
}

// // 时间格式化
// const formatTime = (time) => {
//     return dayjs(time).format('YYYY-MM-DD HH:mm')
// }
</script>

<style scoped>
.chat-container {
    height: 100vh;
}

.left-panel {
    border-right: 1px solid #eee;
    padding: 20px;
}

.consult-item {
    padding: 15px;
    cursor: pointer;
    border-bottom: 1px solid #eee;

    &.active {
        background-color: #f5f7fa;
    }
}

.message-area {
    height: 70vh;
    padding: 20px;
}

/* 新增样式调整 */
.message-bubble {
  margin: 12px 0;
  padding: 8px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.message-id {
  font-size: 0.8em;
  color: #666;
  display: block;
  margin-bottom: 4px;
}

.message-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  p {
    margin: 0;
    flex-grow: 1;
    padding-right: 15px;
  }
}

.time {
  font-size: 0.8em;
  color: #999;
  white-space: nowrap;
}

/* 保持原有颜色区分 */
.self .message-content {
  background: #409eff;
  color: white;
  padding: 8px;
  border-radius: 8px;
}

.input-area {
    display: flex;
    gap: 10px;
    padding: 20px;
    border-top: 1px solid #eee;
}


</style>